using Microsoft.EntityFrameworkCore;
using RiceShop.Models;

namespace RiceShop.Services
{
    /// <summary>
    /// 商品服务接口
    /// </summary>
    public interface IGoodService
    {
        /// <summary>
        /// 获取商品列表，支持分页、分类筛选和关键词搜索
        /// </summary>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="categoryId">分类ID（可选）</param>
        /// <param name="keyword">搜索关键词（可选）</param>
        /// <returns>返回商品列表和总数</returns>
        Task<(List<Good> Items, int Total)> GetGoodsAsync(int pageSize, int pageIndex, long? categoryId = null, string? keyword = null);

        /// <summary>
        /// 获取商品详情，包含SKU信息
        /// </summary>
        /// <param name="spuId">商品SPU ID</param>
        /// <returns>商品详细信息</returns>
        Task<Good?> GetGoodDetailAsync(long spuId);

        /// <summary>
        /// 获取商品分类列表
        /// </summary>
        /// <returns>分类列表</returns>
        Task<List<Category>> GetCategoriesAsync();

        /// <summary>
        /// 获取商品评论列表
        /// </summary>
        /// <param name="spuId">商品SPU ID</param>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">页码</param>
        /// <returns>评论列表和总数</returns>
        Task<(List<Comment> Items, int Total)> GetGoodCommentsAsync(long spuId, int pageSize, int pageIndex);

        /// <summary>
        /// 创建新商品
        /// </summary>
        /// <param name="good">商品信息</param>
        /// <returns>创建的商品</returns>
        Task<Good> CreateGoodAsync(Good good);

        /// <summary>
        /// 更新商品信息
        /// </summary>
        /// <param name="spuId">商品SPU ID</param>
        /// <param name="good">更新的商品信息</param>
        /// <returns>更新后的商品</returns>
        Task<Good> UpdateGoodAsync(long spuId, Good good);


        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="spuId">商品SPU ID</param>
        /// <returns>是否删除成功</returns>
        Task<bool> DeleteGoodAsync(long spuId);

        /// <summary>
        /// 检查商品是否存在
        /// </summary>
        /// <param name="spuId">商品SPU ID</param>
        /// <returns>是否存在</returns>
        Task<bool> GoodExistsAsync(long spuId);

        /// <summary>
        /// 根据ID获取商品信息
        /// </summary>
        /// <param name="spuId">商品SPU ID</param>
        /// <returns>商品信息</returns>
        Task<Good?> GetGoodByIdAsync(long spuId);

        /// <summary>
        /// 根据ID获取SKU信息
        /// </summary>
        /// <param name="skuId">SKU ID</param>
        /// <returns>SKU信息</returns>
        Task<SKU?> GetSkuByIdAsync(long skuId);
    }

    /// <summary>
    /// 商品服务实现类
    /// 提供商品的增删改查、分类、评论等功能
    /// </summary>
    public class GoodService : IGoodService
    {
        private readonly ApplicationDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public GoodService(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取商品列表，支持分页、分类筛选和关键词搜索
        /// </summary>
        public async Task<(List<Good> Items, int Total)> GetGoodsAsync(int pageSize, int pageIndex, long? categoryId = null, string? keyword = null)
        {
            // 构建基础查询，排除已删除商品
            var query = _context.Goods.Where(g => g.IsDeleted != true);

            // 按分类筛选
            if (categoryId.HasValue)
            {
                query = query.Where(g => g.CateId == categoryId.Value);
            }

            // 按关键词搜索
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(g => g.Title != null && g.Title.Contains(keyword));
            }

            var total = await query.CountAsync();
            var items = await query
                .OrderByDescending(g => g.SpuId)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            return (items, total);
        }

        /// <summary>
        /// 获取商品详情，包含SKU信息
        /// </summary>
        public async Task<Good?> GetGoodDetailAsync(long spuId)
        {
            var good = await _context.Goods
                .Include(g => g.Specs)
                .Include(g => g.SpecValues)
                .Include(g => g.Skus)
                .Where(g => g.SpuId == spuId && g.IsDeleted != true)
                .FirstOrDefaultAsync();

            return good;
        }

        /// <summary>
        /// 获取商品分类列表
        /// </summary>
        public async Task<List<Category>> GetCategoriesAsync()
        {
            return await _context.Categories
                .Where(c => c.ParentId == null && c.IsDeleted != true)
                .OrderBy(c => c.Sort)
                .ToListAsync();
        }

        /// <summary>
        /// 获取商品评论列表
        /// </summary>
        public async Task<(List<Comment> Items, int Total)> GetGoodCommentsAsync(long spuId, int pageSize, int pageIndex)
        {
            var query = _context.Comments
                .Where(c => c.SpuId == spuId && !c.IsDeleted);

            var total = await query.CountAsync();
            var items = await query
                .OrderByDescending(c => c.CreateTime)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .Include(c => c.User)
                .ToListAsync();

            return (items, total);
        }

        /// <summary>
        /// 创建新商品
        /// </summary>
        public async Task<Good> CreateGoodAsync(Good good)
        {
            using var transaction = await _context.Database.BeginTransactionAsync();
            try
            {
                // 保存临时的关联数据
                var tempSpecs = good.Specs?.ToList();
                var tempSpecValues = good.SpecValues?.ToList();
                var tempSkus = good.Skus?.ToList();

                // 清空关联集合
                good.Specs = new List<Spec>();
                good.SpecValues = new List<SpecValue>();
                good.Skus = new List<SKU>();

                // 设置基本属性
                good.CreateTime = DateTime.Now;
                good.UpdateTime = DateTime.Now;
                good.IsDeleted = false;

                // 根据规格和SKU的情况设置OpenSpec
                bool hasSpecs = tempSpecs?.Any() == true;
                bool hasSkus = tempSkus?.Any() == true;
                good.OpenSpec = (hasSpecs || hasSkus) ? 1 : 0;

                good.SpuStockQuantity ??= 0; // 确保库存有默认值

                // 添加商品
                _context.Goods.Add(good);
                await _context.SaveChangesAsync();

                // 处理规格
                if (tempSpecs?.Any() == true)
                {
                    foreach (var spec in tempSpecs)
                    {
                        spec.SpuId = good.SpuId;
                        _context.Specs.Add(spec);
                    }
                    good.Specs = tempSpecs;
                }

                // 处理规格值
                if (tempSpecValues?.Any() == true)
                {
                    foreach (var specValue in tempSpecValues)
                    {
                        specValue.SpuId = good.SpuId;
                        _context.SpecValues.Add(specValue);
                    }
                    good.SpecValues = tempSpecValues;
                }

                // 处理SKU
                if (tempSkus?.Any() == true)
                {
                    foreach (var sku in tempSkus)
                    {
                        sku.SpuId = good.SpuId;
                        sku.CreateTime = DateTime.Now;
                        sku.UpdateTime = DateTime.Now;
                        sku.IsDeleted = false;
                        _context.Skus.Add(sku);
                    }
                    good.Skus = tempSkus;
                }

                await _context.SaveChangesAsync();
                await transaction.CommitAsync();
                return good;
            }
            catch
            {
                await transaction.RollbackAsync();
                throw;
            }
        }

        /// <summary>
        /// 更新商品信息
        /// </summary>
        public async Task<Good> UpdateGoodAsync(long spuId, Good good)
        {
            using var transaction = await _context.Database.BeginTransactionAsync();
            try
            {
                var existingGood = await _context.Goods
                   .Include(g => g.Specs)
                   .Include(g => g.SpecValues)
                   .Include(g => g.Skus)
                   .FirstOrDefaultAsync(g => g.SpuId == spuId && g.IsDeleted != true);

                if (existingGood == null)
                {
                    throw new ArgumentException("商品不存在", nameof(spuId));
                }

                // 更新商品基本信息
                _context.Entry(existingGood).CurrentValues.SetValues(good);
                existingGood.UpdateTime = DateTime.UtcNow;
                existingGood.IsDeleted = false;

                // 根据规格和SKU的情况设置OpenSpec
                bool hasSpecs = good.Specs != null && good.Specs.Any();
                bool hasSkus = good.Skus != null && good.Skus.Any();
                existingGood.OpenSpec = (hasSpecs || hasSkus) ? 1 : 0;

                // 更新规格
                if (good.Specs != null)
                {
                    // 删除不再存在的规格
                    var specIdsToKeep = good.Specs.Select(s => s.SpecId).ToList();
                    var specsToRemove = existingGood.Specs
                        .Where(s => !specIdsToKeep.Contains(s.SpecId))
                        .ToList();

                    foreach (var spec in specsToRemove)
                    {
                        _context.Specs.Remove(spec);
                    }

                    // 更新或添加规格
                    foreach (var spec in good.Specs)
                    {
                        var existingSpec = existingGood.Specs
                            .FirstOrDefault(s => s.SpecId == spec.SpecId);

                        if (existingSpec == null)
                        {
                            spec.SpuId = spuId;
                            _context.Specs.Add(spec);
                        }
                        else
                        {
                            _context.Entry(existingSpec).CurrentValues.SetValues(spec);
                        }
                    }
                }
                else
                {
                    // 如果规格为空，删除所有现有规格
                    _context.Specs.RemoveRange(existingGood.Specs);
                }

                // 更新规格值
                if (good.SpecValues != null)
                {
                    // 删除不再存在的规格值
                    var valueIdsToKeep = good.SpecValues.Select(v => v.ValueId).ToList();
                    var valuesToRemove = existingGood.SpecValues
                        .Where(v => !valueIdsToKeep.Contains(v.ValueId))
                        .ToList();

                    foreach (var value in valuesToRemove)
                    {
                        _context.SpecValues.Remove(value);
                    }

                    // 更新或添加规格值
                    foreach (var value in good.SpecValues)
                    {
                        var existingValue = existingGood.SpecValues
                            .FirstOrDefault(v => v.ValueId == value.ValueId);

                        if (existingValue == null)
                        {
                            _context.SpecValues.Add(value);
                        }
                        else
                        {
                            _context.Entry(existingValue).CurrentValues.SetValues(value);
                        }
                    }
                }
                else
                {
                    // 如果规格值为空，删除所有现有规格值
                    _context.SpecValues.RemoveRange(existingGood.SpecValues);
                }

                // 更新SKU
                if (good.Skus != null && good.Skus.Any())
                {
                    // 获取要保留的SKU IDs
                    var skuIdsToKeep = good.Skus.Where(s => s.SkuId != 0).Select(s => s.SkuId).ToList();

                    // 获取需要删除的SKU
                    var skusToRemove = await _context.Skus
                        .Where(s => s.SpuId == spuId && !skuIdsToKeep.Contains(s.SkuId))
                        .ToListAsync();

                    // 删除不再需要的SKU
                    _context.Skus.RemoveRange(skusToRemove);

                    // 更新添加SKU
                    foreach (var sku in good.Skus)
                    {
                        if (sku.SkuId == 0)
                        {
                            // 新SKU
                            sku.SpuId = spuId;
                            sku.CreateTime = DateTime.UtcNow;
                            sku.UpdateTime = DateTime.UtcNow;
                            sku.IsDeleted = false;
                            _context.Skus.Add(sku);
                        }
                        else
                        {
                            // 更新现有SKU
                            var existingSku = await _context.Skus
                                .FirstOrDefaultAsync(s => s.SkuId == sku.SkuId && s.SpuId == spuId);

                            if (existingSku != null)
                            {
                                sku.SpuId = spuId;
                                sku.UpdateTime = DateTime.UtcNow;
                                sku.CreateTime = existingSku.CreateTime; // 保留原始创建时间
                                sku.IsDeleted = false;
                                _context.Entry(existingSku).CurrentValues.SetValues(sku);
                            }
                        }
                    }
                }
                else
                {
                    // 如果SKU为空，删除所有现有SKU
                    var skusToRemove = await _context.Skus
                        .Where(s => s.SpuId == spuId)
                        .ToListAsync();
                    _context.Skus.RemoveRange(skusToRemove);
                }

                await _context.SaveChangesAsync();
                await transaction.CommitAsync();
                return existingGood;
            }
            catch
            {
                await transaction.RollbackAsync();
                throw;
            }
        }



        /// <summary>
        /// 删除商品
        /// </summary>
        public async Task<bool> DeleteGoodAsync(long spuId)
        {
            var good = await _context.Goods.FindAsync(spuId);
            if (good == null)
            {
                return false;
            }

            // 软删除
            good.IsDeleted = true;
            good.UpdateTime = DateTime.UtcNow;
            await _context.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 检查商品是否存在
        /// </summary>
        public async Task<bool> GoodExistsAsync(long spuId)
        {
            return await _context.Goods
                .AnyAsync(g => g.SpuId == spuId && g.IsDeleted != true);
        }

        /// <summary>
        /// 根据ID获取商品信息
        /// </summary>
        /// <param name="spuId">商品SPU ID</param>
        /// <returns>商品信息</returns>
        public async Task<Good?> GetGoodByIdAsync(long spuId)
        {
            return await _context.Goods
                .Include(g => g.Skus)
                .FirstOrDefaultAsync(g => g.SpuId == spuId && g.IsDeleted != true);
        }

        /// <summary>
        /// 根据ID获取SKU信息
        /// </summary>
        /// <param name="skuId">SKU ID</param>
        /// <returns>SKU信息</returns>
        public async Task<SKU?> GetSkuByIdAsync(long skuId)
        {
            return await _context.Skus
                .Include(s => s.Good)
                .FirstOrDefaultAsync(s => s.SkuId == skuId && s.IsDeleted != true);
        }
    }

}